Reorder log files

Time: O(NLog(NxL)); Space: O(L); easy

You have an array of logs.

Each log is a space delimited string of words.

For each log, the first word in each log is an alphanumeric identifier. Then, either:

Each word after the identifier will consist only of lowercase letters, or; Each word after the identifier will consist only of digits. We will call these two varieties of logs letter-logs and digit-logs. It is guaranteed that each log has at least one word after its identifier.

Reorder the logs so that all of the letter-logs come before any digit-log. The letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties. The digit-logs should be put in their original order.

Return the final order of the logs.

Example 1:

Input: logs = [“dig1 8 1 5 1”,“let1 art can”,“dig2 3 6”,“let2 own kit dig”,“let3 art zero”]

Output: [“let1 art can”,“let3 art zero”,“let2 own kit dig”,“dig1 8 1 5 1”,“dig2 3 6”]

Constraints:

  1. 0 <= len(logs) <= 100

  2. 3 <= len(logs[i]) <= 100

  3. logs[i] is guaranteed to have an identifier, and a word after the identifier.

1. Custom Sort

Intuition and Algorithm

Instead of sorting in the default order, we’ll sort in a custom order we specify.

The rules are: * Letter-logs come before digit-logs; * Letter-logs are sorted alphanumerically, by content then identifier; * Digit-logs remain in the same order.

It is straightforward to translate these ideas into code.

[5]:
class Solution1(object):
    """
    Time:  O(nlogn * l), n is the length of files, l is the average length of strings
    Space: O(l)
    """
    def reorderLogFiles(self, logs):
        """
        :type logs: List[str]
        :rtype: List[str]
        """
        def f(log):
            i, content = log.split(" ", 1)
            return (0, content, i) if content[0].isalpha() else (1,)

        logs.sort(key=f)

        return logs
[6]:
s = Solution1()

logs = [
    "dig1 8 1 5 1",
    "let1 art can",
    "dig2 3 6",
    "let2 own kit dig",
    "let3 art zero"
]
assert s.reorderLogFiles(logs) == [
    "let1 art can",
    "let3 art zero",
    "let2 own kit dig",
    "dig1 8 1 5 1",
    "dig2 3 6"
]
[7]:
import string

class Solution2(object):
    def reorderLogFiles(self, logs):
        """
        :type logs: List[str]
        :rtype: List[str]
        """
        letter_logs = []
        digital_logs = []

        for line in logs:
            if line.split(' ')[1][0] in string.digits:
                digital_logs.append(line)
            else:
                letter_logs.append(line)

        letter_logs.sort(key=lambda s: s.split(' ')[1:] + [s.split(' ')[0]])

        return letter_logs + digital_logs
[8]:
s = Solution2()

logs = [
    "dig1 8 1 5 1",
    "let1 art can",
    "dig2 3 6",
    "let2 own kit dig",
    "let3 art zero"
]
assert s.reorderLogFiles(logs) == [
    "let1 art can",
    "let3 art zero",
    "let2 own kit dig",
    "dig1 8 1 5 1",
    "dig2 3 6"
]